<script setup>
import { ref } from 'vue';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { imgUrl } from "../../../utils/global";
import { nextTick } from "vue";
import { deleteCustomersApi, getCustomerListApi } from "@/api/customer";
import { useUserStore } from "../../../store/user";

const userStore = useUserStore();

const data = ref([]);
const isSelectMode = ref(false); // 选择模式状态
const selectedItems = ref([]); // 已选择的项目ID数组

// 获取客户列表数据
const loadCustomerList = async () => {
  try {
    const results = await getCustomerListApi({
      uid: userStore.userInfo.id
    });
    data.value = results[0];
  } catch (error) {
    console.error('getCustomerList', error);
    uni.showToast({
      title: '获取列表失败',
      icon: 'error'
    });
  }
};

// 页面显示时刷新数据（包括从其他页面返回）
onShow(async () => {
  await nextTick();
  await loadCustomerList();
});

const showDetail = (id = null) => {
  uni.navigateTo({
    url: `/pages/profile/customer_detail/index?id=${id || -1}`
  });
}

const handleIdNumber = (number) => {
  if (!number) return '';
  return number.slice(0, 4) + '*'.repeat(number.length - 8) + number.slice(-4);
}

// 切换选择模式
const toggleSelectMode = () => {
  isSelectMode.value = !isSelectMode.value;
  if (!isSelectMode.value) {
    selectedItems.value = []; // 退出选择模式时清空已选择项目
  }
}

// 切换项目选择状态
const toggleItemSelection = (itemId) => {
  const index = selectedItems.value.indexOf(itemId);
  if (index > -1) {
    selectedItems.value.splice(index, 1);
  } else {
    selectedItems.value.push(itemId);
  }
}

// 判断项目是否已被选择
const isItemSelected = (itemId) => {
  return selectedItems.value.includes(itemId);
}

// 删除选中的项目
const deleteSelectedItems = () => {
  if (selectedItems.value.length === 0) {
    uni.showToast({
      title: '请先选择要删除的信息',
      icon: 'none'
    });
    return;
  }


  uni.showModal({
    title: '删除确认',
    content: `已选择 ${selectedItems.value.length} 个信息，确认删除吗？`,
    success: async (res) => {
      if (res.confirm) {
        const ids = Object.values(selectedItems.value);

        try {
          await deleteCustomersApi({
            id: ids
          });
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });

          isSelectMode.value = false;
          selectedItems.value = [];
          loadCustomerList();
        } catch (error) {
          console.error('deleteCustomers error', error);
          uni.showToast({
            title: '删除失败',
            icon: 'error'
          })
        }
      }
    }
  });
}

</script>

<template>
  <view class="app-customer">
    <view class="customer-header">
      <text @click="toggleSelectMode">{{ isSelectMode ? '取消' : '选择' }}</text>
      <text @click="isSelectMode ? deleteSelectedItems() : showDetail()" :class="{ 'delete-btn': isSelectMode }">
        {{ isSelectMode ? '删除' : '添加' }}
      </text>
    </view>

    <view class="customer-list">
      <view class="list-wrapper">
        <text>当前用户</text>
        <view class="list-item" v-for="(item, index) in data.filter(item => item.relationship === '本人')" :key="index">
          <view class="item-left">
            <text>{{ item.name }}</text>
            <text>{{ handleIdNumber(item.certificatenumber) }}</text>
          </view>

          <!-- 选择模式下显示多选按钮 -->
          <view v-if="isSelectMode" class="select-checkbox" @click="toggleItemSelection(item.id)">
            <view class="checkbox-inner" :class="{ 'selected': isItemSelected(item.id) }">
              <text v-if="isItemSelected(item.id)" class="checkmark">✓</text>
            </view>
          </view>

          <!-- 非选择模式下显示编辑图标 -->
          <image v-else :src="imgUrl('/static/img/icons/edit-icon-active.png')" mode="aspectFill"
            @click="showDetail(item.id)" />
        </view>
      </view>

      <view class="list-wrapper">
        <text>其他用户</text>
        <view class="list-item" v-for="(item, index) in data.filter(item => item.relationship !== '本人')" :key="index">
          <view class="item-left">
            <text>{{ item.name }}</text>
            <text>{{ handleIdNumber(item.certificatenumber) }}</text>
          </view>

          <!-- 选择模式下显示多选按钮 -->
          <view v-if="isSelectMode" class="select-checkbox" @click="toggleItemSelection(item.id)">
            <view class="checkbox-inner" :class="{ 'selected': isItemSelected(item.id) }">
              <text v-if="isItemSelected(item.id)" class="checkmark">✓</text>
            </view>
          </view>

          <!-- 非选择模式下显示编辑图标 -->
          <image v-else :src="imgUrl('/static/img/icons/edit-icon-active.png')" mode="aspectFill"
            @click="showDetail(item.id)" />
        </view>
      </view>
    </view>
  </view>
</template>

<style src="./style.scss" scoped />
